﻿using Microsoft.Owin;
using Newtonsoft.Json;
using Serilog;
using System;
using System.Net;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Sustainalytics.RiskRatings.Service.Infrastructure
{
    public class OwinAuthorizationMiddleware : OwinMiddleware
    {
        public OwinAuthorizationMiddleware(OwinMiddleware next) : base(next) { }

        public override async Task Invoke(IOwinContext context)
        {
            try
            {
                var user = (ClaimsPrincipal)context.Request.User;

                if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
                    HandleUnauthorized(context);
                else 
                    await Next.Invoke(context);
            }
            catch (Exception ex)
            {
                Log.Error(ex, "RiskRatings");
            }
        }

        private void HandleUnauthorized(IOwinContext context)
        {
            var errorDataModel = new { Message = "You are not authorized to perform this operation!" };
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            context.Response.ReasonPhrase = "Internal Server Error";
            context.Response.ContentType = "application/json";
            context.Response.Write(JsonConvert.SerializeObject(errorDataModel));
        }
    }
}
